package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author 24040
 * @name MyRedisIdWorker
 * @date 2022-09-13 21:13
 */
@Component
public class MyRedisIdWorker {
    /**
     * 开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1640995200;//开始时间

    private static final long COUNT_BITS = 32;//序列号位数


    private StringRedisTemplate stringRedisTemplate;


    public MyRedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    public long nextId(String prefixKey){
        //1.获取当前时间辍，根据 现在时间- 某个特定的时间点
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        //2.利用redis的incr 命令生成序列号，这个序列号默认应该是从0开始
        String date =  now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long increment = stringRedisTemplate.opsForValue().increment("irc:" + prefixKey + ":" + date);//这样可以根据每天，每月来统计key的数量

        //3.进行拼接
        return timestamp << COUNT_BITS | increment;
    }
}
